package com.wanghlme.day25.sax;

import com.wanghlme.day25.pojo.Student;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;

public class SaxHandler extends DefaultHandler {
    private List<Student> results;
    private Student stu;
    private String eleName;

    public List<Student> getResults() {
        return results;
    }

    public void setResults(List<Student> results) {
        this.results = results;
    }

    @Override
    public void startDocument() throws SAXException {
        System.out.println("startDocument");
        results = new ArrayList<>();
    }

    @Override
    public void endDocument() throws SAXException {
        System.out.println("endDocument");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.println("startElement");
        eleName = qName;
        if ("stu".equals(qName)) {
            stu = new Student();
            String id = attributes.getValue("id");
            stu.setId(id);
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.println("endElement");
        if ("stu".equals(qName)) {
            results.add(stu);
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        System.out.println("characters");
        String value = new String(ch, start, length);
        if ("name".equals(eleName)) {
            stu.setName(value);
        } else if ("weapon".equals(eleName)) {
            stu.setWeapon(value);
        }
        eleName = "";
    }
}
